package org.pitest.ant;

import org.apache.tools.ant.types.Path;
import org.pitest.ant.util.PathUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Aidan Morgan
 */
public class SourceDirs {
  private static Logger s_log = Logger.getLogger(SourceDirs.class.getName());

  private PitestAntTask task;
  private List<Path> paths;

  public SourceDirs(PitestAntTask task) {
    this.task = task;
    this.paths = new ArrayList<Path>();
  }

  public List<Path> getDirectories() {
    return Collections.unmodifiableList(paths);
  }

  public Path createPath() {
    Path p = new Path(task.getProject());
    paths.add(p);

    return p;
  }

  public String asString(String seperator) {
    StringBuffer buff = new StringBuffer();
    String sep = "";

    for (String s : asList()) {
      buff.append(sep);
      buff.append(s);

      sep = seperator;
    }

    return buff.toString();
  }

  public List<String> asList() {
    List<String> result = new ArrayList<String>();

    for (final Path p : paths) {
      List<File> res = PathUtils.convertPath(p);

      for (File fr : res) {
        try {
          result.add(fr.getCanonicalPath());
        } catch (IOException e) {
          if (s_log.isLoggable(Level.WARNING)) {
            s_log.log(Level.WARNING, "IOException thrown for source directory " + fr.getAbsolutePath() + ". This directory will be skipped.", e);
          }
        }
      }
    }

    return result;
  }

  public int size() {
    return asList().size();
  }
}
